
#include <arpa/inet.h>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>

namespace wzh
{
  class udpServer
  {
  public:
    udpServer(const int port) : _port(port)  
    {}
    ~udpServer() {}
    void init()
    {
      _sock = socket(AF_INET, SOCK_DGRAM, 0);
      if (_sock < 0)
      {
        std::cout << "create failed\n";
        exit(-1);
      }
      struct sockaddr_in addr;
      addr.sin_addr.s_addr = INADDR_ANY;
      addr.sin_family = AF_INET;
      addr.sin_port = htons(_port);

      if (bind(_sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
      {
        std::cout << "bind failed\n";
        exit(-1);
      }
    }

    void run()
    {
      struct sockaddr_in clientaddr;
      socklen_t addrlen = sizeof(clientaddr);
      while (1)
      {
        char buffer[1024];
        int ret = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&clientaddr, &addrlen);
        if (ret > 0)
        {
          buffer[ret] = '\0';
          std::cout << "recv : " << buffer << std::endl;
          sendto(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
        }
        else if (ret == 0)
        {
          std::cout << "client quit.....\n";
          break;
        }
        else
        {
          std::cout << "recv failed\n";
          exit(-1);
        }
      }
    }

  private:
    int _sock;
    int _port;
  };
}
